#!/usr/bin/env python
# -*- coding: utf-8 -*-

__copyright__ = "Copyright (C) 2008 Nando Florestan"

import random, os


def get_random_letters(count):
    """Returns a string of random letters.
    The parameter "count" determines the size of the returned string.
    """
    s = []
    for i in xrange(0, count):
        s.append(chr(random.randint(97, 122)))
    return "".join(s)



_char_repl = dict(
    a = u'áàâãäå',
    e = u'éèêẽë',
    i = u"íìîĩï",
    o = u'óòôõöø',
    u = u"úùûũü",
    A = u'ÁÀÂÃÄÅ',
    E = u'ÉÈÊẼË',
    I = u"ÍÌÎĨÏ",
    O = u'ÓÒÔÕÖØ',
    U = u"ÚÙÛŨÜ",
    n = u"ñ",
    c = u"ç",
    N = u"Ñ",
    C = u"Ç",
    d = u"Þ",
    ss = u"ß",
    ae = u"æ",
    oe = u'œ',
)

def to_ascii(txt):
    '''Removes from *txt* (a unicode string) all extended,
    non-ASCII characters, replacing common accented characters.
    '''
    u = txt
    for plain, funny in _char_repl.items():
        for f in funny:  u = u.replace(f, plain)
    return u.encode('ASCII','ignore')

def to_filename(txt, for_web=False, sep='-'):
    '''Massages *txt* until it is a good filename.'''
    illegal = u'\\/\t:?"<>|#$%&*[]•'
    for c in illegal:  txt = txt.replace(c, '')
    txt = to_ascii(txt.strip())
    if for_web:
        txt = txt.replace(' ', sep).replace('--', sep).lower()
    return txt

def find_new_title(dir, filename):
    """If file *filename* exists in directory *dir*, adds or changes the
    end of the file title until a name is found that doesn't yet exist.
    Returns the new file name (without directory).
    For instance, if file "Image (01).jpg" exists, returns "Image (02).jpg"."""
    rx = re.compile(r"\((\d{1,5})\)$")
    #if not os.path.isdir(dir):  os.makedirs(dir)
    p = os.path.join(dir, filename)
    while os.path.exists(p):
        base = os.path.basename(p)
        (root, ext) = os.path.splitext(base)
        m = rx.search(root)
        if m == None:
            replacement = "(001)"
        else:
            increment = int(m.group(1)) + 1
            replacement = "(%03d)" % increment
            root = root[:m.start(1)-1]
        f = root + replacement + ext
        p = os.path.join(dir, f)
    return p



# HTML section
# ============

def encode_xml_char_refs(s):
    # http://mail.python.org/pipermail/python-list/2007-January/424262.html
    return s.encode('ascii', 'xmlcharrefreplace')

from htmlentitydefs import name2codepoint
import re

def _replace_entity(m):
     s = m.group(1)
     if s[0] == u'#':
         s = s[1:]
         try:
             if s[0] in u'xX':
                 c = int(s[1:], 16)
             else:
                 c = int(s)
             return unichr(c)
         except ValueError:
             return m.group(0)
     else:
         try:
             return unichr(name2codepoint[s])
         except (ValueError, KeyError):
             return m.group(0)

_entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
def decode_xml_char_refs(s):
     return _entity_re.sub(_replace_entity, s)

def test_xml_char_refs():
    s = u"© áéíóú ãẽõ ôâ à ü"
    t = encode_xml_char_refs(s)
    u = decode_xml_char_refs(t)
    # print u
    assert s == u, "Conversion to XML char refs and back failed!"


if __name__ == "__main__":
    print "Testing conversion to XML char refs."
    test_xml_char_refs()
